<!-- CommentList.vue -->
<template>
  <div class="comment-section">
    <!-- Header with rating summary -->
    <div class="comment-header">
      <div class="header-main">
        <div class="header-title">
          <h2>
            <i class="icon-comment"></i>
            {{ typeof spot === 'object' ? spot.spotName : spot }}的评价
          </h2>
          <span class="review-count">{{ totalReviews }}条评价</span>
        </div>
        <a class="view-all" href="javascript:void(0)">
          更多评论 <i class="icon-arrow"></i>
        </a>
      </div>

      <div class="rating-summary">
        <div class="rating-score">
          <div class="score">{{ rating }}</div>
          <div class="score-details">
            <div class="max-score">/5</div>
            <div class="rating-label">{{ getRatingText(rating) }}</div>
          </div>
        </div>

        <div class="rating-distribution">
          <!-- Rating distribution bars could go here in a future enhancement -->
        </div>

        <button class="write-review-btn" @click="showRatingForm = true" v-if="!showRatingForm">
          <i class="icon-pen"></i> 写评价
        </button>
      </div>
    </div>

    <!-- Rating form -->
    <div class="rating-form-container" v-if="showRatingForm">
      <div class="rating-form">
        <h3>分享您的体验</h3>

        <div class="star-rating-container">
          <div class="star-rating">
            <span v-for="star in 5" :key="star" class="star"
                  :class="{ 'active': star <= userRating }"
                  @click="setRating(star)">
              ★
            </span>
          </div>
          <span class="rating-value">{{ userRating ? userRating : 0 }}/5</span>
        </div>

        <textarea
            v-model="newComment"
            placeholder="请分享您的体验细节，帮助其他用户做出决定..."
            class="comment-textarea"
        ></textarea>

        <div class="upload-container">
          <p class="upload-label">添加照片</p>

          <el-upload
              action="#"
              list-type="picture-card"
              :auto-upload="false"
              :on-preview="handlePictureCardPreview"
              :on-change="handleFileChange"
              :on-remove="handleFileRemove"
              :limit="9"
              v-model:file-list="fileList"
          >
            <template #default>
              <div class="upload-icon-container">
                <i class="el-icon-plus"></i>
                <span>添加图片</span>
              </div>
            </template>
          </el-upload>

          <el-dialog v-model="dialogVisible" title="预览">
            <img :src="dialogImageUrl" alt="Preview Image" style="width: 100%;" />
          </el-dialog>

          <div class="form-actions upload-actions" v-if="fileList.length > 0">
            <button class="cancel-button" @click="clearUpload">清空图片</button>
          </div>
        </div>

        <div class="form-actions">
          <button class="cancel-button" @click="cancelRating">取消</button>
          <button class="submit-button" @click="submitComment" :disabled="!userRating">
            发布评价
          </button>
        </div>
      </div>
    </div>

    <!-- Comment filter tabs -->
    <div class="comment-filters">
      <div class="filter-tab" :class="{ 'active': activeTab === 'all' }" @click="activeTab = 'all'">
        全部 ({{ totalReviews || 0 }})
      </div>
      <div class="filter-tab" :class="{ 'active': activeTab === 'newest' }" @click="activeTab = 'newest'">
        最新
      </div>
      <div class="filter-tab" :class="{ 'active': activeTab === 'pictures' }" @click="activeTab = 'pictures'">
        附图 ({{ getCommentsWithPictures() }})
      </div>
      <div class="filter-tab" :class="{ 'active': activeTab === 'positive' }" @click="activeTab = 'positive'">
        好评 ({{ getPositiveComments() }})
      </div>
      <div class="filter-tab" :class="{ 'active': activeTab === 'negative' }" @click="activeTab = 'negative'">
        差评 ({{ getNegativeComments() }})
      </div>
    </div>

    <!-- Comment list -->
    <div class="comment-list">
      <comment-item
          v-for="comment in filteredComments"
          :key="comment.remarkId"
          :comment="comment"
          @reply="handleReply"
          @like="handleLike"
      ></comment-item>
    </div>
  </div>
</template>

<script>
import { ref, computed, watch } from 'vue';
import { ElMessage } from 'element-plus';
import CommentItem from './CommentItem.vue';
import { useStore } from 'vuex';
import { addComment } from '@/api/comment';
import axios from "axios";

export default {
  name: 'CommentList',
  components: {
    CommentItem
  },
  props: {
    commentData: {
      type: Array,
      required: true
    },
    rating: {
      type: [Number, String],
      default: 0
    },
    totalReviews: {
      type: [Number, String],
      default: 0
    },
    spot: {
      type: [Object, String],
      default: '景点'
    },
    triggerParentFn: {
      type: Function,
      default: () => {''}
    }
  },
  setup(props, { emit }) {
    const store = useStore();
    const comments = ref([]);
    const newComment = ref('');
    const showRatingForm = ref(false);
    const userRating = ref(0);
    const activeTab = ref('all');
    const fileList = ref([]);
    const uploadedImages = ref([]);
    const dialogImageUrl = ref('');
    const dialogVisible = ref(false);
    const selectedFile = ref(null);

    // Initialize and watch comment data
    watch(() => props.commentData, (newVal) => {
      comments.value = JSON.parse(JSON.stringify(newVal));
    }, { immediate: true, deep: true });

    // Get rating text based on score
    const getRatingText = (score) => {
      score = Number(score);
      if (score >= 4.5) return '很棒';
      if (score >= 4.0) return '推荐';
      if (score >= 3.5) return '不错';
      if (score >= 3.0) return '一般';
      if (score >= 2.0) return '较差';
      return '很差';
    };

    // Method for previewing images
    const handlePictureCardPreview = (file) => {
      dialogImageUrl.value = file.url || URL.createObjectURL(file.raw);
      dialogVisible.value = true;
    };

    // Enhanced file change handler
    const handleFileChange = (file) => {
      // Check file size (limit to 5MB for example)
      if (file.size > 5 * 1024 * 1024) {
        ElMessage.warning('图片大小不能超过5MB！');
        return false;
      }

      // Check file type
      const isImage = file.raw.type.indexOf('image/') !== -1;
      if (!isImage) {
        ElMessage.warning('只能上传图片文件！');
        return false;
      }

      // Create preview URL
      const reader = new FileReader();
      reader.readAsDataURL(file.raw);
      reader.onload = () => {
        // Store the base64 for preview and later upload
        const index = fileList.value.findIndex(item => item.uid === file.uid);
        if (index !== -1) {
          fileList.value[index].url = reader.result;
          uploadedImages.value.push({
            uid: file.uid,
            url: reader.result,
            file: file.raw
          });
        }
      };

      return true;
    };

    // Handle file removal
    const handleFileRemove = (file, fileList) => {
      const index = uploadedImages.value.findIndex(item => item.uid === file.uid);
      if (index !== -1) {
        uploadedImages.value.splice(index, 1);
      }
    };

    // Method to clear upload
    const clearUpload = () => {
      fileList.value = [];
      uploadedImages.value = [];
    };

    // Method to upload all images
    const handleBatchUpload = async () => {
      if (fileList.value.length === 0) {
        ElMessage.warning('请先选择要上传的图片！');
        return;
      }

      const uploadPromises = uploadedImages.value.map(image => {
        const formData = new FormData();
        formData.append("file", image.file);

        return axios.post("/api/upload", formData, {
          headers: { "Content-Type": "multipart/form-data" }
        });
      });

      try {
        ElMessage.info('正在上传图片，请稍候...');
        const responses = await Promise.all(uploadPromises);

        // Store image URLs returned from server
        const imageUrls = responses.map(response => response.data);

        // If you need to display or use these URLs, you can store them
        uploadedImages.value = imageUrls.map((url, index) => ({
          uid: uploadedImages.value[index].uid,
          url: url
        }));

        ElMessage.success('图片上传成功！');

      } catch (error) {
        ElMessage.error('上传失败: ' + error.message);
      }
    };

    // 保留原有的上传方法以兼容现有逻辑
    const handleUpload = (event) => {
      selectedFile.value = event.target.files[0];
    };

    const submit = async () => {
      if (!selectedFile.value) return;

      const formData = new FormData();
      formData.append("file", selectedFile.value);

      try {
        const response = await axios.post("/api/upload", formData, {
          headers: { "Content-Type": "multipart/form-data" }
        });

        const imageUrl = response.data; // 如: "/images/abc123.jpg"
        console.log("访问地址:", window.location.origin + imageUrl);
      } catch (error) {
        ElMessage.error("上传失败: " + error.message);
      }
    };

    // Get comments with pictures count
    const getCommentsWithPictures = () => {
      return comments.value.filter(comment =>
          comment.picture && comment.picture.length > 0).length;
    };

    // Get positive comments count
    const getPositiveComments = () => {
      return comments.value.filter(comment =>
          comment.score && comment.score >= 4).length;
    };

    // Get negative comments count
    const getNegativeComments = () => {
      return comments.value.filter(comment =>
          comment.score && comment.score < 3).length;
    };

    // Set rating
    const setRating = (star) => {
      userRating.value = star;
    };

    // Cancel rating
    const cancelRating = () => {
      fileList.value = [];
      uploadedImages.value = [];
      showRatingForm.value = false;
      userRating.value = 0;
      newComment.value = '';
      fileList.value = [];
      uploadedImages.value = [];
    };

    // Submit comment
    const submitComment = async () => {
      if (fileList.value.length === 0) {
        ElMessage.warning('请先选择要上传的图片！');
        return;
      }

      const uploadPromises = uploadedImages.value.map(image => {
        const formData = new FormData();
        formData.append("file", image.file);

        return axios.post("/api/upload", formData, {
          headers: {"Content-Type": "multipart/form-data"}
        });
      });

      try {
        ElMessage.info('正在上传图片，请稍候...');
        const responses = await Promise.all(uploadPromises);

        // Store image URLs returned from server
        const imageUrls = responses.map(response => response.data);

        // If you need to display or use these URLs, you can store them
        uploadedImages.value = imageUrls.map((url, index) => ({
          uid: uploadedImages.value[index].uid,
          url: url
        }));

        ElMessage.success('图片上传成功！');

      } catch (error) {
        ElMessage.error('上传失败: ' + error.message);
      }
      // ——————————————————————————————————————————————————
      if (!userRating.value) {
        ElMessage.warning('请给出您的评分！');
        return;
      }

      if (!newComment.value.trim() && uploadedImages.value.length === 0) {
        ElMessage.warning('评论内容不能为空！');
        return;
      }

      // Create new comment object
      const newCommentObj = {
        remark: newComment.value,
        score: userRating.value,
        reLike: 0,
        reDate: new Date().toLocaleDateString(),
        picture: uploadedImages.value.map(img => img.url),
        userId: store.state.userInfo?.userId,
        bindId: typeof props.spot === 'object' ? props.spot.spotId : null,
        status: 0
      };

      console.log(`output->newComment`, newCommentObj);

      // Use API to submit comment
      addComment(newCommentObj).then((res) => {
        ElMessage.success({
          message: '评论提交成功！',
          type: 'success',
          duration: 2000
        });

        // Call parent refresh function
        props.triggerParentFn();

        // Reset form
        resetForm();
      }).catch(err => {
        ElMessage.error('评论提交失败，请稍后重试');
      });
    };

    // Reset form
    const resetForm = () => {
      newComment.value = '';
      fileList.value = [];
      uploadedImages.value = [];
      userRating.value = 0;
      showRatingForm.value = false;
    };

    // Handle reply
    const handleReply = (remarkId, replyContent) => {
      const findAndAddReply = (commentList) => {
        for (let i = 0; i < commentList.length; i++) {
          if (commentList[i].remarkId === remarkId) {
            const replyComment = {
              remarkId: Date.now(),
              user: {
                userId: store.state.userInfo?.userId || 1,
                userName: store.state.userInfo?.userName || "当前用户",
                avatar: store.state.userInfo?.avatar || "/images/default-avatar.jpg"
              },
              bindId: commentList[i].bindId,
              remark: replyContent,
              picture: [],
              reDate: new Date().toISOString(),
              reLike: 0,
              status: 0,
              score: null,
              comments: [],
              showReplyBox: false
            };

            if (!commentList[i].comments) {
              commentList[i].comments = [];
            }

            commentList[i].comments.push(replyComment);

            emit('reply-added', {
              parentId: remarkId,
              reply: replyComment
            });

            return true;
          }

          if (commentList[i].comments && commentList[i].comments.length > 0) {
            if (findAndAddReply(commentList[i].comments)) {
              return true;
            }
          }
        }

        return false;
      };

      findAndAddReply(comments.value);
    };

    // Handle like
    const handleLike = (remarkId) => {
      const findAndLike = (commentList) => {
        for (let i = 0; i < commentList.length; i++) {
          if (commentList[i].remarkId === remarkId) {
            commentList[i].reLike = (commentList[i].reLike || 0) + 1;

            emit('comment-liked', {
              remarkId: remarkId,
              likes: commentList[i].reLike
            });

            return true;
          }

          if (commentList[i].comments && commentList[i].comments.length > 0) {
            if (findAndLike(commentList[i].comments)) {
              return true;
            }
          }
        }

        return false;
      };

      findAndLike(comments.value);
    };

    // Filter comments based on active tab
    const filteredComments = computed(() => {
      if (activeTab.value === 'all') return comments.value;
      if (activeTab.value === 'newest') {
        return [...comments.value].sort((a, b) => {
          if (!a.reDate) return 1;
          if (!b.reDate) return -1;
          return new Date(b.reDate) - new Date(a.reDate);
        });
      }
      if (activeTab.value === 'pictures') {
        return comments.value.filter(comment =>
            comment.picture && comment.picture.length > 0);
      }
      if (activeTab.value === 'positive') {
        return comments.value.filter(comment =>
            comment.score && comment.score >= 4);
      }
      if (activeTab.value === 'negative') {
        return comments.value.filter(comment =>
            comment.score && comment.score < 3);
      }
      return comments.value;
    });

    return {
      comments,
      newComment,
      showRatingForm,
      userRating,
      activeTab,
      fileList,
      uploadedImages,
      selectedFile,
      dialogImageUrl,
      dialogVisible,
      filteredComments,
      getRatingText,
      handlePictureCardPreview,
      handleFileChange,
      handleFileRemove,
      getCommentsWithPictures,
      getPositiveComments,
      getNegativeComments,
      setRating,
      cancelRating,
      submitComment,
      handleReply,
      handleLike,
      handleUpload,
      submit,
      clearUpload,
      handleBatchUpload
    };
  }
};
</script>
<style scoped>
img {
  width: 20px; /* Force 25% of original width */
  height: auto !important; /* Maintain aspect ratio */
  max-width: 5% !important; /* Ensure maximum width is also 25% */
  object-fit: contain; /* Ensure the entire image is visible */
}
.comment-section {
  width: 100%; /* Take full width of parent */
  overflow-y: auto; /* Enable vertical scrolling for overflow content */
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
  color: #333;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  padding: 24px;
  margin: 20px 0;
  box-sizing: border-box; /* Include padding in width calculation */
}

/* Header Styles */
.comment-header {
  position: sticky;
  top: 0;
  background-color: #fff;
  z-index: 10;
  padding-bottom: 20px;
  margin-bottom: 12px;
}

.header-main {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title {
  display: flex;
  align-items: baseline;
  gap: 12px;
}

.header-title h2 {
  font-size: 22px;
  font-weight: 600;
  margin: 0;
  color: #262626;
  display: flex;
  align-items: center;
  gap: 8px;
}

.icon-comment {
  color: #10b981;
  font-size: 20px;
}

.icon-comment:before {
  content: "💬";
}

.review-count {
  color: #6b7280;
  font-size: 14px;
}

.view-all {
  color: #10b981;
  font-size: 14px;
  text-decoration: none;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 4px;
  transition: color 0.2s;
}

.view-all:hover {
  color: #059669;
}

.icon-arrow:before {
  content: "→";
}

/* Rating Summary */
.rating-summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.rating-score {
  display: flex;
  align-items: center;
  gap: 12px;
  background-color: #f3f4f6;
  padding: 16px 20px;
  border-radius: 12px;
}

.score {
  font-size: 36px;
  font-weight: 700;
  color: #10b981;
  line-height: 1;
}

.score-details {
  display: flex;
  flex-direction: column;
}

.max-score {
  font-size: 16px;
  color: #6b7280;
  margin-bottom: 4px;
}

.rating-label {
  font-size: 16px;
  font-weight: 600;
  color: #10b981;
}

.rating-distribution {
  flex-grow: 1;
  margin: 0 24px;
}

.write-review-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  background-color: #10b981;
  color: white;
  font-size: 15px;
  font-weight: 500;
  padding: 12px 20px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.write-review-btn:hover {
  background-color: #059669;
}

.icon-pen:before {
  content: "✏️";
  font-size: 14px;
}

/* Rating Form */
.rating-form-container {
  margin-bottom: 32px;
  max-height: 70%;
  overflow-y: auto;
}

.rating-form {
  background-color: #f9fafb;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.rating-form h3 {
  font-size: 18px;
  font-weight: 600;
  color: #262626;
  margin: 0 0 20px 0;
}

.star-rating-container {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.star-rating {
  display: flex;
  gap: 4px;
}

.star {
  font-size: 28px;
  color: #d1d5db;
  cursor: pointer;
  transition: color 0.2s;
}

.star:hover, .star.active {
  color: #fbbf24;
}

.rating-value {
  margin-left: 16px;
  font-size: 15px;
  color: #6b7280;
  font-weight: 500;
}

.comment-textarea {
  width: 100%;
  min-height: 120px;
  padding: 16px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  font-family: inherit;
  font-size: 15px;
  color: #374151;
  resize: vertical;
  margin-bottom: 20px;
  transition: border-color 0.2s;
}

.comment-textarea:focus {
  border-color: #10b981;
  outline: none;
}

.upload-container {
  margin-bottom: 24px;
}

.upload-label {
  font-size: 15px;
  font-weight: 500;
  color: #374151;
  margin-bottom: 12px;
}

.upload-icon-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 4px;
  color: #6b7280;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.upload-actions {
  margin-top: 16px;
}

.cancel-button {
  padding: 10px 16px;
  font-size: 14px;
  font-weight: 500;
  color: #4b5563;
  background-color: #fff;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.cancel-button:hover {
  background-color: #f3f4f6;
}

.submit-button {
  padding: 10px 20px;
  font-size: 14px;
  font-weight: 500;
  color: white;
  background-color: #10b981;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.submit-button:hover {
  background-color: #059669;
}

.submit-button:disabled {
  background-color: #9ca3af;
  cursor: not-allowed;
}

/* Comment Filters */
.comment-filters {
  position: sticky;
  top: 120px; /* Adjust based on your header height */
  background-color: #fff;
  z-index: 5;
  padding: 8px 0;
  margin-bottom: 16px;
  display: flex;
  gap: 8px;
  overflow-x: auto;
  white-space: nowrap;
}

.filter-tab {
  font-size: 14px;
  color: #4b5563;
  padding: 8px 16px;
  border-radius: 20px;
  background-color: #f3f4f6;
  cursor: pointer;
  white-space: nowrap;
  transition: all 0.2s;
}

.filter-tab.active {
  background-color: #10b981;
  color: white;
  font-weight: 500;
}

.filter-tab:hover:not(.active) {
  background-color: #e5e7eb;
}

/* Comment List */
.comment-list {
  max-height: calc(100% - 200px); /* Adjust based on your header size */
  overflow-y: auto;
  margin-top: 24px;
}

/* Element UI Adjustments */
:deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
  line-height: 100px;
  border-radius: 8px;
  border: 1px dashed #d9d9d9;
  display: flex;
  justify-content: center;
  align-items: center;
}

:deep(.el-upload--picture-card:hover) {
  border-color: #10b981;
  color: #10b981;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 100px;
  height: 100px;
  border-radius: 8px;
  transition: all 0.3s;
}

:deep(.el-upload-list--picture-card .el-upload-list__item:hover) {
  transform: scale(1.05);
}

:deep(.el-icon-plus) {
  font-size: 24px;
  color: #909399;
  margin-bottom: 4px;
}

@media (max-width: 768px) {
  .comment-section {
    height: 500px; /* Slightly smaller fixed height on mobile */
    padding: 16px;
  }

  .comment-filters {
    top: 100px; /* Adjust for smaller header on mobile */
  }

  .rating-summary {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .rating-score {
    width: 100%;
    justify-content: center;
  }

  .write-review-btn {
    width: 100%;
    justify-content: center;
  }
}
</style>